<template>
	<view>
		<view class="content" @touchstart="hideDrawer">
			<scroll-view class="msg-list" scroll-y="true" :scroll-with-animation="scrollAnimation" :scroll-top="scrollTop"
			 :scroll-into-view="scrollToView" @scrolltoupper="loadHistory" upper-threshold="50">
				<view v-show="isLoadData" class="mescroll-downwarp">
					<view class="downwarp-content">
						<view class="downwarp-progress"></view>
					</view>
				</view>
				<view class="row" v-for="(row,index) in msgList" :key="index" :id="'msg'+row.msg.id">
					<view class="m-time" v-if="row.msg.numtime>10">
						<view class="font-size24 color-9A9A9A">{{row.msg.time}}</view>
					</view>
					<!-- 系统消息 -->
					<block v-if="row.type=='system'">
						<view class="system">
							<!-- 文字消息 -->
							<view v-if="row.msg.type=='text'" class="text">
								{{row.msg.content.text}}
							</view>
						</view>
					</block>
					<!-- 用户消息 -->
					<block v-if="row.type=='user'">
						<!-- 发出的消息 -->
						<view class="my" v-if="row.msg.userinfo.uid==myuid">
							<!-- 左-消息 -->
							<view class="left">
								<!-- 文字消息 -->
								<view v-if="row.msg.type=='text'" class="bubble bubblew padding-15">
									<text>{{row.msg.content.text}}</text>
									<image v-for="(item,i) in row.msg.content.emoji" :key="i" :src="item" style="width: 24px;height: 24px;"></image>
								</view>
								<!-- 语言消息 -->
								<view v-if="row.msg.type=='voice'" class="bubble bubblew voice padding-15" @tap="playVoice(row.msg)" :class="playMsgid == row.msg.id?'play':''">
									<view class="length">{{row.msg.content.length}}</view>
									<view class="icon my-voice"></view>
								</view>
								<!-- 图片消息 -->
								<view v-if="row.msg.type=='image'" class="bubble bubblew image" @tap="showPic(row.msg)">
									<image lazy-load="true" :src="row.msg.content.thumbnail" :style="{'width': row.msg.content.w+'px','height': row.msg.content.h+'px'}"
									 style="border-radius: 10upx;"></image>
								</view>
							</view>
							<!-- 右-头像 -->
							<view class="right">
								<image lazy-load="true" :src="row.msg.userinfo.face"></image>
							</view>
						</view>
						<!-- 收到的消息 -->
						<view class="other" v-if="row.msg.userinfo.uid!=myuid">
							<!-- 左-头像 -->
							<view class="left">
								<image lazy-load="true" :src="row.msg.userinfo.face"></image>
							</view>
							<!-- 右-用户名称-时间-消息 -->
							<view class="right">
								<!-- 文字消息 -->
								<view v-if="row.msg.type=='text'" class="bubble padding-15">
									<text>{{row.msg.content.text}}</text>
									<image lazy-load="true" v-for="(item,i) in row.msg.content.emoji" :key="i" :src="item" style="width: 24px;height: 24px;"></image>
								</view>
								<!-- 语音消息 -->
								<view v-if="row.msg.type=='voice'" class="bubble voice padding-15" @tap="playVoice(row.msg)" :class="playMsgid == row.msg.id?'play':''">
									<view class="icon other-voice"></view>
									<view class="length">{{row.msg.content.length}}</view>
								</view>
								<!-- 图片消息 -->
								<view v-if="row.msg.type=='image'" class="bubble image" @tap="showPic(row.msg)">
									<image lazy-load="true" :src="row.msg.content.thumbnail" :style="{'width': row.msg.content.w+'px','height': row.msg.content.h+'px'}"
									 style="border-radius: 10upx;"></image>
								</view>
							</view>
						</view>
					</block>
				</view>
			</scroll-view>
		</view>
		<!-- 抽屉栏 -->
		<view class="popup-layer" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<!-- 表情 -->
			<swiper class="emoji-swiper" :class="{hidden:hideEmoji}" indicator-dots="true" duration="150">
				<swiper-item v-for="(page,pid) in emojiList" :key="pid">
					<view v-for="(em,eid) in page" :key="eid" @tap="addEmoji(em)">
						<image mode="widthFix" :src="'/static/image/emoji/'+em.url"></image>
					</view>
				</swiper-item>
			</swiper>
			<!-- 更多功能 相册-拍照 -->
			<view class="more-layer" :class="{hidden:hideMore}">
				<view class="list">
					<view class="box" @tap="chooseImage">
						<view id="file" class="icon tupian2"></view>
					</view>
					<view class="box" @tap="camera">
						<view id="file" class="icon paizhao"></view>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部输入栏 -->
		<view class="input-box" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<!-- H5下不能录音，输入栏布局改动一下 -->
			<!-- #ifndef H5 -->
			<view class="voice">
				<!-- 语音 -->
				<view class="icon" :class="isVoice?'jianpan':'yuyin'" @tap="switchVoice"></view>
			</view>
			<!-- #endif -->
			<view class="textbox">
				<!-- 输入框 -->
				<!-- #ifdef H5 -->
				<view class="em" @tap="chooseEmoji">
					<!-- 表情按钮 -->
					<view class="icon biaoqing"></view>
				</view>
				<!-- #endif -->
				<view class="voice-mode" :class="[isVoice?'':'hidden',recording?'recording':'']" @touchstart="voiceBegin"
				 @touchmove.stop.prevent="voiceIng" @touchend="voiceEnd" @touchcancel="voiceCancel">{{voiceTis}}</view>
				<view class="text-mode" :class="isVoice?'hidden':''">
					<view class="box">
						<textarea auto-height="true" :cursor-spacing="8" maxlength="500" v-model="textMsg" @focus="textareaFocus" @blur="hideSend" />
						</view>
				</view>
				<!-- #ifndef H5 -->
				<view class="em" @tap="chooseEmoji"><!-- 表情按钮 -->
					<view class="icon biaoqing"></view>
				</view>
				<!-- #endif -->
			</view>
			<!-- #ifdef H5 -->
			<view class="more" @tap="showMore"><!-- 加号按钮 -->
				<view class="icon add"></view>
			</view>
			<!-- #endif -->
			<!-- #ifndef H5 -->
			<!-- v-if="!sendLook" -->
			<view class="more"  @tap="showMore" style="margin-right: 10upx;"><!-- 加号按钮 -->
				<view class="icon add"></view>
			</view>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<!--  -->
			<view class="send" :class="isVoice?'hidden':''"  @tap="sendText"><!-- 发送按钮 -->
				<view class="btn">发送</view>
			</view>
			<!-- #endif -->
			
			<!-- #ifndef H5 -->
			<view class="send" :class="isVoice?'hidden':''"  @tap="sendText"><!-- 发送按钮 -->
				<view class="btn">发送</view>
			</view>
			<!-- #endif -->
		</view>
		<!-- 录音UI效果 -->
		<view class="record" :class="recording?'':'hidden'">
			<view class="ing" :class="willStop?'hidden':''"><view class="icon luyin2" ></view></view>
			<view class="cancel" :class="willStop?'':'hidden'"><view class="icon chehui" ></view></view>
			<view class="tis" :class="willStop?'change':''">{{recordTis}}</view>
		</view>
	</view>
</template>
<script>
	import jnpf from '@/common/js/jnpf.js'
	import helper from '@/common/js/helper.js'
	import config from '@/common/js/config.js'
	import {mapState,mapMutations} from 'vuex'
	export default {
		data() {
			return {
				//文字消息
				textMsg:'',
				//消息列表
				isHistoryLoading:false,
				scrollAnimation:false,
				scrollTop:0,
				scrollToView:'',
				telHeight:0,
				inbTop:0,
				mesBot:0,
				sendLook:false,
				msgList:[],
				msgimageList:[],
				myuid:0,
				//录音相关参数
				// #ifndef H5
				//H5不能录音
				RECORDER:uni.getRecorderManager(),
				// #endif
				isVoice:false,
				voiceTis:'按住 说话',
				recordTis:"手指上滑 取消发送",
				recording:false,
				willStop:false,
				initPoint:{identifier:0,Y:0},
				recordTimer:null,
				recordLength:0,
				//播放语音相关参数
				// #ifndef MP-ALIPAY
				AUDIO:uni.createInnerAudioContext(),
				// #endif
				playMsgid:null,
				VoiceTimer:null,
				// 抽屉参数
				popupLayerClass:'',
				// more参数
				hideMore:true,
				//表情定义
				hideEmoji:true,
				emojiList:[
					[{"url":"100.gif",alt:"[微笑]"}]
				],
				friendId:null,
				param:{},
				isLoadData:true
			};
		},
		computed:{
			sendmsg: function() {
				let sendMessage= this.$store.state.wschat.sendMessage;
				if (sendMessage.length!=0) {
					let msg =this.msgList.length==0?0: this.msgList[this.msgList.length-1].msg;
					let lastid = msg.id;
					for (let i = 0; i < sendMessage.length; i++) {
						lastid++;
						sendMessage[i].msg.id=lastid;
						sendMessage[i].msg.numtime=msg==0?60:helper.timeDifference(msg.datetime,sendMessage[i].msg.datetime);
						this.screenMsg(sendMessage[i])
					}
					sendMessage.length=0
				}
				
				return sendMessage;
			},
			
			receivemsg: function() {
				let receiveMessage= this.$store.state.wschat.receiveMessage;
				if (receiveMessage.length!=0) {
					let msg =this.msgList.length==0?0: this.msgList[this.msgList.length-1].msg;
					let lastid = msg.id;
					for (let i = 0; i < receiveMessage.length; i++) {
						lastid++;
						receiveMessage[i].msg.id=lastid;
						receiveMessage[i].msg.numtime=msg==0?60:helper.timeDifference(msg.datetime,receiveMessage[i].msg.datetime);
						this.screenMsg(receiveMessage[i])
					}
					receiveMessage.length=0;
				}
				
				return receiveMessage
			},
		},
		watch:{
			sendmsg(newValue, oldValue) {},
			receivemsg(newValue, oldValue) {}
		},
		onLoad(option) {
			this.sendmsg.length = 0;
			this.receivemsg.length = 0;
			this.friendId = option.friendId;
			uni.setNavigationBarTitle({
				title: option.name
			});
			// #ifndef MP-ALIPAY
			uni.hideTabBarRedDot({
				index : 1,
			})
			// #endif
			//语音自然播放结束
			// #ifndef MP-ALIPAY
			this.AUDIO.onEnded((res)=>{
				this.playMsgid=null;
			});
			// #endif
			
			// #ifndef H5 || MP-ALIPAY
			//录音开始事件
			this.RECORDER.onStart((e)=>{
				this.recordBegin(e);
			});
			//录音结束事件
			this.RECORDER.onStop((e)=>{
				this.recordEnd(e);
			});
			// #endif
			
			// setTimeout(() =>{
			// 	this.getMessageList();
			// 	this.isLoadData=false;
			// }, 300);
			
			this.getMessageList();
			this.isLoadData=false
			
		},
		onShow(){
			this.scrollTop = 9999999;
		},
		onUnload() {
			this.unfriend();
			// #ifndef MP-ALIPAY
			this.AUDIO.stop();
			// #endif
		},
		methods:{
			...mapMutations(['unfriend']),
			screenMsg(msg){		// 接受消息(筛选处理)
				if(msg.type=='system'){
					// 系统消息
					this.addSystemTextMsg(msg);
				}else if(msg.type=='user'){
					
					if (this.friendId!=null&&msg.method==="receiveMessage") {
						try {
							const token = uni.getStorageSync(config.Global.cache + '_Token');
							if (token) {
								const msg = JSON.stringify({
									method: "UpdateReadMessage",
									token: token,
									formUserId: this.friendId
								});
								helper.sendSocketMessage(msg);
								const badge = uni.getStorageSync(config.Global.cache + '_Badge');
								let badgen = badge - msg.count;
								uni.setStorage({
									key: config.Global.cache + '_Badge',
									data: badgen
								});
							}
						}catch (e) {}
					}
					// 用户消息
					switch (msg.msg.type){
						case 'text':
							this.replaceEmoji(msg.msg.content);
							this.addTextMsg(msg);
							break;
						case 'voice':
							this.addVoiceMsg(msg);
							break;
						case 'image':
							this.addimageMsg(msg);
							break;
						case 'redEnvelope':
							this.addRedEnvelopeMsg(msg);
							break;
					}
				}
				this.$nextTick(function() {
					// 滚动到底
					this.scrollToView = 'msg'+msg.msg.id
				});
			},
			loadHistory(e){		//触发滑动到顶部(加载历史信息记录)
				try {
					this.sendmsg.length = 0;
					this.receivemsg.length = 0;
					const userProvider = uni.getStorageSync(config.Global.cache + '_UserProvider');
					if (this.param.total > this.param.page) {
						this.param.page += 1;
						if (this.friendId!=null&&userProvider.userId!='') {
							const token = uni.getStorageSync(config.Global.cache + '_Token');
							if (token) {
								const msg = JSON.stringify({
									method: "MessageList",
									token: token,
									toUserId: this.friendId,
									formUserId: userProvider.userId,
									currentPage: this.param.page,
									pageSize: 15,
									sord: "desc"
								});
								helper.sendSocketMessage(msg);
							}
							this.getMessageList();
						}
					}
				}catch (e) {}
			},
			getLoadHistory(msgHistory){
				if(this.isHistoryLoading){
					return ;
				}
				this.isHistoryLoading = true;//参数作为进入求标识，防止重复求
				this.scrollAnimation = false;//关闭滑动动画
				let Viewid = this.msgList[0].msg.id;//记住第一个信息ID
				
				setTimeout(()=>{
					if (msgHistory.length>0) {
						let list =msgHistory;
						// 获取消息中的图片,并处理显示尺寸
						for(let i=list.length-1;i>=0;i--){
							if(list[i].type=='user'&&list[i].msg.type=="image"){
								list[i].msg.content = this.setPicSize(list[i].msg.content);
								this.msgimageList.unshift(list[i].msg.content.url);
							}
							if(list[i].type=='user'&&list[i].msg.type=="text"){
								this.replaceEmoji(list[i].msg.content);
							}
							list[i].msg.id = Math.floor(Math.random()*1000+1);
							this.msgList.unshift(list[i]);
						}
					}
					//这段代码很重要，不然每次加载历史数据都会跳到顶部
					this.$nextTick(function() {
						this.scrollToView = 'msg'+Viewid;//跳转上次的第一行信息位置
						this.$nextTick(function() {
							this.scrollAnimation = true;//恢复滚动动画
						});
					});
					this.isLoadData=false;
					this.isHistoryLoading = false;
				},1000)
			},
			
			// 加载初始页面消息
			getMsgList(msgInitialize){	
				console.log('加载初始页面消息',msgInitialize)
				if (msgInitialize!=undefined) {
					for(let i=0;i<msgInitialize.length;i++){
						if(msgInitialize[i].type=='user'&&msgInitialize[i].msg.type=="image"){
							msgInitialize[i].msg.content = this.setPicSize(msgInitialize[i].msg.content);
							this.msgimageList.push(msgInitialize[i].msg.content.url);
						}
						if(msgInitialize[i].type=='user'&&msgInitialize[i].msg.type=="text"){
							this.replaceEmoji(msgInitialize[i].msg.content);
						}
					}
					this.msgList = msgInitialize;
					this.isLoadData=false;
				}
				// 滚动到底部
				this.$nextTick(function() {
					//进入页面滚动到底部
					this.scrollTop = 9999;
					this.$nextTick(function() {
						this.scrollAnimation = true;
					});
				});
			},
			setPicSize(content){	//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
				// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
				let maxW = uni.upx2px(350);//350是定义消息图片最大宽度
				let maxH = uni.upx2px(350);//350是定义消息图片最大高度
				if(content.w>maxW||content.h>maxH){
					let scale = content.w/content.h;
					content.w = scale>1?maxW:maxH*scale;
					content.h = scale>1?maxW/scale:maxH;
				}
				return content;
			},
			showMore(){			//更多功能(点击+弹出) 
				this.isVoice = false;
				this.hideEmoji = true;
				if(this.hideMore){
					this.hideMore = false;
					this.openDrawer();
				}else{
					this.hideDrawer();
				}
			},
			openDrawer(){		// 打开抽屉
				this.popupLayerClass = 'showLayer';
			},
			hideDrawer(){		// 隐藏抽屉
				this.popupLayerClass = '';
				setTimeout(()=>{
					this.hideMore = true;
					this.hideEmoji = true;
				},150);
			},
			chooseImage(){		// 选择图片发送
				this.getImage('album');
			},
			camera(){			//拍照发送
				this.getImage('camera');
			},
			getImage(type){		//选照片 or 拍照
				this.hideDrawer();
				uni.chooseImage({
					// #ifdef H5
					count:1,
					// #endif
					sourceType:[type],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res)=>{
						for(let i=0;i<res.tempFilePaths.length;i++){
							uni.getImageInfo({
								src: res.tempFilePaths[i],
								success: (image)=>{
									// #ifdef MP-WEIXIN
									wx.getFileSystemManager().readFile({
										filePath: image.path,
										encoding:"base64",
										success: (data)=>{
											let msg = {
												base64:data.data,
												width:image.width,
												height:image.height,
											};
											this.sendMsg(msg,'image');
										},
									});
									// #endif
									// #ifdef APP-PLUS
									let path=plus.io.convertLocalFileSystemURL(image.path);
									let fileReader = new plus.io.FileReader();
									fileReader.readAsDataURL(path);
									fileReader.onloadend = (evt)=> {
										let msg = {
											base64:evt.target.result.replace(/data:image\/.*;base64,/,''),
											width:image.width,
											height:image.height,
										};
										this.sendMsg(msg,'image');
									}
									// #endif
									// #ifdef H5
									let file = document.getElementsByTagName("input")[0].files[0];
									let reader = new FileReader();
									reader.readAsDataURL(file);
									reader.onload=(e)=>{
										let msg = {
											base64:e.target.result.replace(/data:image\/.*;base64,/,''),
											width:image.width,
											height:image.height,
										};
										this.sendMsg(msg,'image');
									}
									// #endif
								}
							});
						}
					}
				});
			},
			chooseEmoji(){		// 选择表情
				this.hideMore = true;
				if(this.hideEmoji){
					this.hideEmoji = false;
					this.openDrawer();
				}else{
					this.hideDrawer();
				}
			},
			addEmoji(em){		//添加表情
				this.textMsg+=em.alt;
			},
			textareaFocus(){	//获取焦点，如果不是选表情ing,则关闭抽屉
				this.sendLook=true;
				if(this.popupLayerClass=='showLayer' && this.hideMore == false){
					this.hideDrawer();
				}
			},
			hideSend(){
				this.sendLook=false;
			},
			/* 点击发送按钮 */
			sendText(){// 发送文字消息
			
				this.hideDrawer();//隐藏抽屉
				if(!this.textMsg){
					return;
				}
				let content = this.textMsg;
				let msg = {text:content}
				this.sendMsg(msg,'text');
				this.textMsg = '';//清空输入框
			},
			
			replaceEmoji(str){	//替换表情符号为图片
			
				let replacedStr = str.text.replace(/\[([^(\]|\[)]*)\]/g,(item, index)=>{
					for(let i=0;i<this.emojiList.length;i++){//循环表情列表
						let row = this.emojiList[i];
						for(let j=0;j<row.length;j++){
							let EM = row[j];
							if(EM.alt==item){
								let onlinePath = "/static/image/emoji/"+EM.url
								str.emoji.push(onlinePath)
								return '';
							}else{
								return item;
							}
						}
					}
				});
				
				str.text=replacedStr;
			},
			
			sendMsg(content,type){	// 发送消息
				const _this = this;
				try {
					let messageObj;
					const token = uni.getStorageSync(config.Global.cache + '_Token');
					if (token) {
						switch (type){
							case 'text':
								messageObj = {
									method: "SendMessage",
									token:token,
									toUserId: this.friendId,
									messageType:"text",
									messageContent: content.text
								};
								break;
							case 'voice':
								messageObj = {
									method: "SendMessage",
									token:token,
									toUserId: this.friendId,
									messageType:"voice",
									messageContent: content
								};
								break;
							case 'image':
								messageObj = {
									method: "SendMessage",
									token:token,
									toUserId: this.friendId,
									messageType:"image",
									messageContent: content
								};
								break;
							default:
								break;
						}
						const msg = JSON.stringify(messageObj);
						
						helper.sendSocketMessage(msg);
					}
				}catch (e) {}
			},
			addTextMsg(msg){		// 添加文字消息到列表
				this.msgList.push(msg);
			},
			addVoiceMsg(msg){		// 添加语音消息到列表
				this.msgList.push(msg);
			},
			addimageMsg(msg){		// 添加图片消息到列表
				msg.msg.content = this.setPicSize(msg.msg.content);
				this.msgimageList.push(msg.msg.content.url);
				this.msgList.push(msg);
			},
			addRedEnvelopeMsg(msg){
				this.msgList.push(msg);
			},
			addSystemTextMsg(msg){			// 添加系统文字消息到列表
				this.msgList.push(msg);
			},
			addSystemRedEnvelopeMsg(msg){	// 添加系统红包消息到列表
				this.msgList.push(msg);
			},
			sendSystemMsg(content,type){
				let lastid = this.msgList[this.msgList.length-1].msg.id;
				lastid++;
				let row = {type:"system",msg:{id:lastid,type:type,content:content}};
				this.screenMsg(row)
			},
			showPic(msg){		// 预览图片
				uni.previewImage({
					indicator:"none",
					current:msg.content.url,
					urls: this.msgimageList
				});
			},
			playVoice(msg){		// 播放语音
				this.AUDIO.stop();
				let apiKey= uni.getStorageSync('apiKey') ||'JAVA';
				let baseUrlObj=config.Global.baseUrl;
				let baseUrl=config.Global.baseUrl[apiKey].apiUrl;
				this.AUDIO.src = baseUrl + "/api/file/Image/IM/" + msg.content.url;
				if (this.playMsgid!=null && this.playMsgid==msg.id) {
					this.$nextTick(()=> {
						this.AUDIO.stop();
					});
					this.playMsgid=null;
				} else{
					this.$nextTick(()=> {
						this.AUDIO.play();
					});
					this.playMsgid=msg.id;
				}
			},
			voiceBegin(e){		// 录音开始
				this.RECORDER.stop();
				if(e.touches.length>1){
					return ;
				}
				this.initPoint.Y = e.touches[0].clientY;
				this.initPoint.identifier = e.touches[0].identifier;
				this.RECORDER.start({format:"mp3"});//录音开始,
			},
			recordBegin(e){		//录音开始UI效果
				this.recording = true;
				this.voiceTis='松开 结束';
				this.recordLength = 0;
				this.recordTimer = setInterval(()=>{
					this.recordLength++;
				},1000)
			},
			voiceCancel(){		// 录音被打断
				this.recording = false;
				this.voiceTis='按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.willStop = true;//不发送录音
				this.RECORDER.stop();//录音结束
			},
			voiceIng(e){		// 录音中(判断是否触发上滑取消发送)
				if(!this.recording){
					return;
				}
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if(this.initPoint.Y - touche.clientY>=uni.upx2px(100)){
					this.willStop = true;
					this.recordTis = '松开手指 取消发送'
				}else{
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送'
				}
			},
			voiceEnd(e){		// 结束录音
				if(!this.recording){
					return;
				}
				this.recording = false;
				this.voiceTis='按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.RECORDER.stop();//录音结束
			},
			recordEnd(e){		//录音结束(回调文件)
				if(!this.willStop){
					let min = parseInt(this.recordLength/60);
					let sec = this.recordLength%60;
					min = min<10?'0'+min:min;
					sec = sec<10?'0'+sec:sec;
					if (sec<'01') {
						this.willStop = true;
						helper.msg('说话时间太短');
						return
					}
					// #ifdef MP-WEIXIN
					wx.getFileSystemManager().readFile({
						filePath: e.tempFilePath,
						encoding:"base64",
						success: (data)=>{
							let msg = {
								base64:data.data,
								length:min+':'+sec
							};
							this.sendMsg(msg,'voice');
						},
					});
					// #endif
					// #ifdef APP-PLUS
					let path=plus.io.convertLocalFileSystemURL(e.tempFilePath);
					let fileReader = new plus.io.FileReader();
					fileReader.readAsDataURL(path);
					fileReader.onloadend = (evt)=> {
						let msg = {
							base64:evt.target.result.replace(/data:audio\/.*;base64,/,''),
							length:min+':'+sec
						};
						this.sendMsg(msg,'voice');
					}
					// #endif
				}else{
					// console.log('取消发送录音');
				}
				this.willStop = false;
			},
			switchVoice(){		// 切换语音/文字输入
				this.hideDrawer();
				this.isVoice = this.isVoice?false:true;
			},
			discard(){
				return;
			},
			//获取消息列表
			getMessageList(){
				setTimeout(()=> {
					try{
						let data= this.$store.state.wschat.messageList;
						console.log('获取消息列表',data)
						let msgList = new Array;
						let apiKey= uni.getStorageSync('apiKey') ||'JAVA';
						let baseUrlObj=config.Global.baseUrl;
						let baseUrl=config.Global.baseUrl[apiKey].apiUrl;
						const userProvider = uni.getStorageSync(config.Global.cache + '_UserProvider');
						if (data!=null) {
							this.param = {
								'page': data.pagination.currentPage,
								'records': data.list,
								'total': data.pagination.total,
								'rows': data.list.length
							}
							for (let i = 0; i < data.list.length; i++) {
								// console.log(data.list[i].sendUserId)
								let j = i - 1;
								let content = {};
								if (data.list[i].contentType != 'text') {
									data.list[i].content = JSON.parse(data.list[i].content);
								}
								
								
								switch (data.list[i].contentType) {
									case 'text':
										content = {
											text: data.list[i].content,
											emoji: []
										}
										break;
									case 'voice':
										content = {
											url: data.list[i].content.path,
											length: data.list[i].content.length
										}
										break;
									case 'image':
										content = {
											thumbnail: baseUrl + "/api/file/Image/IM/T" + data.list[i].content.path,
											url: baseUrl + "/api/file/Image/IM/" + data.list[i].content.path,
											w: data.list[i].content.width,
											h: data.list[i].content.height
										}
										break;
								}
								
								msgList.push({
									type: "user",
									msg: {
										id: i,
										msgId: data.list[i].id,
										type: data.list[i].contentType,
										numtime: j >=0 ? (helper.toDate(data.list[j].sendTime, 'yyyy-MM-dd HH:mm:ss'),
											helper.toDate(data.list[i].sendTime, 'yyyy-MM-dd HH:mm:ss')) :j ==-1?99:0,
										datetime: helper.toDate(data.list[i].sendTime, 'yyyy-MM-dd HH:mm:ss'),
										time: helper.toDate(data.list[i].sendTime, 'yyyy-MM-dd HH:mm:ss'),
										userinfo: {
											uid: userProvider.id == data.list[i].sendUserId ? 0 : 1,
											formId: data.list[i].sendUserId,
											username: jnpf.userData(data.list[i].sendUserId).F_Name,
											face: baseUrl +  jnpf.userData(data.list[i].sendUserId).F_HeadIcon
										},
										content: content
									}
								});
								
							}
							
							if (data.pagination.currentPage == 1) {
								this.isLoadData=true;
								this.getMsgList(msgList);
							} else {
								this.isLoadData=true;
								this.getLoadHistory(msgList);
							}
						}
					}catch(e){
						// console.log("抛出异常：：：",e)
						//TODO handle the exception
					}
				}, 50);
			}
		},
	}
</script>
<style lang="scss">
	@import "@/static/css/style.scss"; 
</style>
